import os, sys, logging
os.environ['DJANGO_SETTINGS_MODULE'] = 'settings'

from google.appengine.dist import use_library
use_library('django', '1.1')

import settings
from django.utils import simplejson

class Ticket(object):
    
    def __init__(self, id, title, owner, labels, hours, status):
        self.id = id
        self.title = title
        self.owner = owner
        if self.owner == '':
            self.owner = 'Unassigned'
        self.labels = labels
        if hours == '':
            self.hours = 1
        else:
            self.hours = int(hours)
        self.status = status
    
    def to_json_object(self):
        return {
            'id': self.id,
            'title': self.title,
            'owner': self.owner,
            'labels': self.labels,
            'hours': self.hours,
            'status': self.status,
        }
        
        

def get(project_id, milestone=None, appengine=False):
    import urllib2
    import csv
    if milestone:
        url = "http://code.google.com/p/%s/issues/csv?can=1&q=Milestone:%s&colspec=ID%%20Status%%20Owner%%20EstimatedTime%%20Summary%%20Milestone" % (project_id, milestone.split('-')[1])
    else:
        url = "http://code.google.com/p/%s/issues/csv?can=2&q=-Milestone&colspec=ID%%20Status%%20Owner%%20EstimatedTime%%20Summary%%20Milestone" % (project_id, )
    f = urllib2.urlopen(url)
    reader = csv.reader(f)
    tickets = []
    i = 0
    for row in reader:
        if i != 0 and len(row):
            labels = row[5].replace('"', "'").split(', ')
            tickets.append(Ticket(row[0].replace('"', "'"), row[4].replace('"', "'"), row[2].replace('"', "'"), labels, row[3].replace('"', "'"), row[1].replace('"', "'")))
        i = i + 1
        
    return tickets

def unassigned_tickets_json(project_id, appengine=False):
    out = []
    for ticket in get(project_id, appengine=appengine):
        out.append(ticket.to_json_object())
    return simplejson.dumps(out).replace("'", "\\'")